package com.qyhl.webtv.module_microvideo.shortvideo.introduction;

import android.Manifest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoIntroductionBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.view.MyScrollView;
import com.qyhl.webtv.commonlib.utils.view.MyWebView;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.shortvideo.ShortVideoActivity;
import com.weavey.loading.lib.LoadingLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */
public class ShortVideoIntroductionFragment extends BaseFragment implements ShortVideoIntroductionContract.ShortVideoIntroductionView {
    @BindView(R2.id.cover)
    ResizableImageView cover;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.person_num)
    TextView personNum;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.webview)
    MyWebView webview;
    @BindView(R2.id.scroll_view)
    MyScrollView scrollView;

    private String activityId;

    private ShortVideoIntroductionBean mData;

    private ShortVideoIntroductionPresenter mPresenter;

    public void setActivityId(String activityId) {
        this.activityId = activityId;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.micro_fragment_short_video_introduction, null);
    }

    @Override
    protected void create() {
        mPresenter = new ShortVideoIntroductionPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getDetail(activityId);
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    public static ShortVideoIntroductionFragment newInstance(String actId) {
        ShortVideoIntroductionFragment fragment = new ShortVideoIntroductionFragment();
        fragment.setActivityId(actId);
        return fragment;
    }



    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
    }

    private void setListeners() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(activityId);
        });

        scrollView.setOnScrollListener(dy -> ((ShortVideoActivity) getActivity()).showHideBottombar(dy));


    }

    @OnClick(R2.id.share_btn)
    public void onViewClicked() {
        if (mData != null) {
            MPermissionUtils.requestPermissionsResult(getActivity(), 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    MShareBoard shareBoard = new MShareBoard(getActivity(), activityId, mData.getName(), mData.getLogo(), "", 25, false, false, true);

                    shareBoard.setToolListener(new MShareBoard.ShareToolListener() {
                        @Override
                        public void collectChange(boolean isCollect) {

                        }

                        @Override
                        public void textSizeChange() {
                            int checkId;
                            switch (SpfManager.getInstance(getContext()).getInt("fontSize", 2)) {
                                case 0:
                                    checkId = R.id.textsize_lv1;
                                    break;
                                case 1:
                                    checkId = R.id.textsize_lv2;
                                    break;
                                case 2:
                                    checkId = R.id.textsize_lv3;
                                    break;
                                case 3:
                                    checkId = R.id.textsize_lv4;
                                    break;
                                case 4:
                                    checkId = R.id.textsize_lv5;
                                    break;
                                default:
                                    checkId = R.id.textsize_lv3;
                                    break;
                            }
                            new OtherDialog.Builder(getContext())
                                    .setContentView(R.layout.micro_dialog_textsize_choice)
                                    .setWidth(0.8f)
                                    .setCanceledOnTouchOutside(true)
                                    .setOnCheckedChangeListener(R.id.dialog_radioGroup, checkId, position -> {
                                        SpfManager.getInstance(getContext()).putInt("fontSize", idToPosition(position));
                                        setFontSize(position);
                                    })
                                    .setDismissButton(R.id.dialog_cancel)
                                    .show();
                        }
                    });

                    shareBoard.showPopupWindow();
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(getActivity());
                }
            });
        } else {
            showToast("暂无分享内容！", 4);
        }
    }

    private int idToPosition(int checkId) {
        int pos = 2;
        if (checkId == R.id.textsize_lv1) {
            pos = 0;
        } else if (checkId == R.id.textsize_lv2) {
            pos = 1;
        } else if (checkId == R.id.textsize_lv3) {
            pos = 2;
        } else if (checkId == R.id.textsize_lv4) {
            pos = 3;
        } else if (checkId == R.id.textsize_lv5) {
            pos = 4;
        }
        return pos;
    }

    @Override
    public void setDetail(ShortVideoIntroductionBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mData = bean;
        Glide.with(getContext())
                .load(bean.getLogo())
                .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                .into(cover);

        title.setText(bean.getName());

        personNum.setText(bean.getParticipateNumber() + "参与");
        initWebView();
        String htmlTxt = "<html><body>" + getNewContent(bean.getInformation()) + "</body></html>";
        webview.loadDataWithBaseURL(null, htmlTxt, "text/html", "utf-8", null);
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("max-width", "100%").attr("max-height", "auto");
            element.attr("style", "max-width:100% !important;max-height:auto !important");
        }
        return doc.toString();
    }

    //初始化webview
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(false);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setBlockNetworkImage(false);
        setFontSize(SpfManager.getInstance(getContext()).getInt("fontSize", 2));
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        if (msg.contains("网络")) {
            loadMask.setErrorImage(R.drawable.error_network);
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
        }
    }

    /**
     * 设置webview字体大小
     */
    private void setFontSize(int position) {
        switch (position) {
            case 0:
                webview.getSettings().setTextZoom(50);
                break;
            case 1:
                webview.getSettings().setTextZoom(75);
                break;
            case 2:
                webview.getSettings().setTextZoom(100);
                break;
            case 3:
                webview.getSettings().setTextZoom(150);
                break;
            case 4:
                webview.getSettings().setTextZoom(200);
                break;
            default:
                break;
        }
    }
}
